﻿using Prism.Ioc;
using Prism.Regions;
using ReactiveUI;
using ReactiveUI.Fody.Helpers;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Reactive;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using WPF_Drawer_Demo.Models;
using WPF_Drawer_Demo.Views;

namespace WPF_Drawer_Demo.ViewModels
{
    public class MainWindowViewModel : ReactiveObject
    {
        [Reactive]
        public ObservableCollection<DataItem> DataList { get; set; }

        private bool _isAddingData;

        private CancellationTokenSource _cancellationTokenSource;

        public ReactiveCommand<Unit, Unit> StartAddingDataCommand { get; }
        public ReactiveCommand<Unit, Unit> StopAddingDataCommand { get; }

        public MainWindowViewModel(IContainerProvider containerProvider)
        {
            containerProvider.Resolve<IRegionManager>().RegisterViewWithRegion<DataView>("Drawer");
            DataList = new ObservableCollection<DataItem>();

            // Initialize commands
            StartAddingDataCommand = ReactiveCommand.Create(StartAddingData);
            StopAddingDataCommand = ReactiveCommand.Create(StopAddingData);

            _isAddingData = false;
        }

        private async void StartAddingData()
        {
            if (_isAddingData)
                return;

            _isAddingData = true;
            _cancellationTokenSource = new CancellationTokenSource();
            var token = _cancellationTokenSource.Token;

            int i = 1;
            while (_isAddingData && !token.IsCancellationRequested)
            {
                DataList.Insert(0, new DataItem
                {
                    Index = i,
                    Name = $"Item {i}",
                    Remark = $"Remark {i}"
                });

                i++;

                try
                {
                    // 延迟1秒
                    await Task.Delay(1000, token);
                }
                catch (TaskCanceledException)
                {
                    // 捕获任务取消异常
                }
            }
        }

        private void StopAddingData()
        {
            _isAddingData = false;
            _cancellationTokenSource?.Cancel();
        }
    }
}
